using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;

namespace Lzfy_Refund_Service.Controllers
{
    /// <summary>
    /// 退费情况查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class RefundStatusController : ControllerBase
    {
        private readonly IRefundStatusService _refundStatusService;
        private readonly ILogger<RefundStatusController> _logger;

        public RefundStatusController(IRefundStatusService refundStatusService, ILogger<RefundStatusController> logger)
        {
            _refundStatusService = refundStatusService;
            _logger = logger;
        }

        /// <summary>
        /// 分页查询退费情况数据
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>分页查询结果</returns>
        /// <response code="200">查询成功</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("query")]
        public async Task<ActionResult<RefundStatusQueryResponse>> Query([FromBody] RefundStatusQueryRequest request)
        {
            try
            {
                if (request == null)
                {
                    return BadRequest(new { message = "请求参数不能为空" });
                }

                // 参数验证和默认值设置
                if (request.PageIndex <= 0)
                    request.PageIndex = 1;
                
                if (request.PageSize <= 0)
                    request.PageSize = 50;

                var response = await _refundStatusService.GetPagedAsync(request);
                
                _logger.LogInformation("退费情况查询成功，页码: {PageIndex}, 每页: {PageSize}, 总数: {TotalCount}", 
                    request.PageIndex, request.PageSize, response.TotalCount);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "退费情况查询失败，页码: {PageIndex}, 每页: {PageSize}", 
                    request?.PageIndex, request?.PageSize);
                return StatusCode(500, new { message = "查询退费情况失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取导出预估信息
        /// </summary>
        /// <param name="request">导出请求</param>
        /// <returns>预估信息</returns>
        /// <response code="200">获取成功</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("export-estimate")]
        public async Task<ActionResult> GetExportEstimate([FromBody] RefundStatusExportRequest request)
        {
            try
            {
                if (request == null)
                {
                    return BadRequest(new { message = "请求参数不能为空" });
                }

                var estimate = await _refundStatusService.GetExportEstimateAsync(request);
                
                var estimatedSizeMB = Math.Round(estimate.EstimatedSizeBytes / 1024.0 / 1024.0, 2);
                
                _logger.LogInformation("获取导出预估信息成功，总记录数: {TotalCount}, 预估大小: {EstimatedSizeMB} MB", 
                    estimate.TotalCount, estimatedSizeMB);

                return Ok(new 
                { 
                    totalCount = estimate.TotalCount, 
                    estimatedSizeBytes = estimate.EstimatedSizeBytes, 
                    estimatedSizeMB,
                    estimatedDurationMinutes = estimate.EstimatedDurationMinutes,
                    message = $"预计导出 {estimate.TotalCount:N0} 条记录，文件大小约 {estimatedSizeMB} MB，预计耗时 {estimate.EstimatedDurationMinutes} 分钟"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取导出预估信息失败");
                return StatusCode(500, new { message = "获取导出预估信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 导出退费情况数据
        /// </summary>
        /// <param name="request">导出请求</param>
        /// <returns>导出文件</returns>
        /// <response code="200">导出成功</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("export")]
        public async Task<IActionResult> Export([FromBody] RefundStatusExportRequest request)
        {
            try
            {
                if (request == null)
                {
                    return BadRequest(new { message = "请求参数不能为空" });
                }

                // 检查导出数据量，如果超过300万条记录，建议分批导出
                var estimate = await _refundStatusService.GetExportEstimateAsync(request);
                var totalCount = estimate.TotalCount;
                if (totalCount > 3000000)
                {
                    _logger.LogWarning("导出数据量过大: {TotalCount} 条记录", totalCount);
                    return BadRequest(new 
                    { 
                        message = $"导出数据量过大（{totalCount:N0} 条记录），建议添加筛选条件或联系管理员",
                        totalCount 
                    });
                }
                
                // 对于大量数据（超过100万条），记录警告日志
                if (totalCount > 1000000)
                {
                    _logger.LogWarning("导出大量数据: {TotalCount} 条记录，可能需要较长时间", totalCount);
                }

                _logger.LogInformation("开始导出退费情况数据，总记录数: {TotalCount}, 格式: {ExportFormat}", 
                    totalCount, request.ExportFormat);

                var fileBytes = await _refundStatusService.ExportAsync(request);

                var fileName = $"退费情况查询_{DateTime.Now:yyyyMMdd_HHmmss}";
                string contentType;
                string fileExtension;
                
                if (request.ExportFormat.ToLower() == "excel")
                {
                    contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    fileExtension = ".xlsx";
                    
                    // 如果数据量超过100万条，文件名标识为多Sheet
                    if (totalCount > 1000000)
                    {
                        fileName += "_多Sheet";
                    }
                }
                else
                {
                    contentType = "text/csv";
                    fileExtension = ".csv";
                }

                _logger.LogInformation("退费情况数据导出完成，文件名: {FileName}", fileName + fileExtension);

                return File(fileBytes, contentType, fileName + fileExtension);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出退费情况数据失败，格式: {ExportFormat}", request?.ExportFormat);
                return StatusCode(500, new { message = "导出退费情况数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取退款结果选项
        /// </summary>
        /// <returns>退款结果选项列表</returns>
        /// <response code="200">获取成功</response>
        [HttpPost("refund-result-options")]
        public ActionResult GetRefundResultOptions()
        {
            try
            {
                var options = new[]
                {
                    new { value = "", label = "全部" },
                    new { value = "已完成退款", label = "已完成退款" },
                    new { value = "部分退款", label = "部分退款" },
                    new { value = "患者余额增加", label = "患者余额增加" },
                    new { value = "未退款", label = "未退款" }
                };

                return Ok(options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取退款结果选项失败");
                return StatusCode(500, new { message = "获取退款结果选项失败", error = ex.Message });
            }
        }
    }
}